package com.yunyike.interceptor;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.yunyike.constants.CommonConstant;
import com.yunyike.model.User;
import com.yunyike.redis.JedisManager;
import com.yunyike.utils.CookieUtils;
import com.yunyike.utils.UserUtils;

public class CommonInterceptor extends HandlerInterceptorAdapter{

	private static Logger log = LoggerFactory.getLogger(CommonInterceptor.class);
	
	@Value("${static_server}")
	public String static_server;
	
	@Value("${server}")
	public String server;
	
	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
	}

	@Override
	public void afterConcurrentHandlingStarted(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		request.setAttribute("static_server", static_server);
		request.setAttribute("server", server);
	}

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		
		User user = getCurrentUser(request);
		// 更新登录状态
		if(user != null){
			doLogin(user, request, response);
		}
		
		return super.preHandle(request, response, handler);
	}

	/**
	 * 获取当前登录的用户
	 * @return
	 */
	private User getCurrentUser(HttpServletRequest request) {
		// 获取用户的cookie
		Cookie cookie = CookieUtils.getCookie(request, CommonConstant.USER_KEY_COOKIE);
		
		if(cookie == null || StringUtils.isBlank(cookie.getValue())){
			return null;
		}
		
		// 根据cookie值获取用户
		User user = (User)JedisManager.getObject(cookie.getValue());
		
		if(user == null){
			return null;
		}
		
		//log.info("----->>current user:"+user);
		
		return user;
	}
	
	/**
	 * 登录
	 * @param user
	 */
	private void doLogin(User user,HttpServletRequest request,
			HttpServletResponse response){

		String sessionId = UserUtils.getSessionId(request, response);
		
		try {
			JedisManager.setObject(sessionId, CommonConstant.USER_KEY_ET, user);
		} catch (Exception e) {
			log.error("set user to redis has errors:message:"+e.getMessage(),e);
		}
	}
}
